import { SO_DISCONNECT, ONLINE_SYS } from '../../const'

const starListener = (io, socket, opts) => {
  const { t } = socket.handshake.query
  let message = ''
  if (!(t in opts.onlineUsers)) {
    opts.onlineUsers[t] = socket.id
    opts.onlineCount ++
  }
  message = '有一个人前来连接'
  let res = {
    message,
    onlineUsers: opts.onlineUsers,
    onlineCount: opts.onlineCount
  }
  // console.log(message + ' : ', res)
  io.emit(ONLINE_SYS, res)
  socket.on(SO_DISCONNECT, () => {
    if (!t) return
    delete opts.onlineUsers[t]
    opts.onlineCount --
    message = '有一个人不连接了'
    res = {
      message,
      onlineUsers: opts.onlineUsers,
      onlineCount: opts.onlineCount
    }
    // console.log(message + ' : ', res)
    io.emit(ONLINE_SYS, res)
  })
}

export default starListener
